
// F. Chaxel 2010

#include <iostream>
using namespace std;

#include "ThreadObject.h"

//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
ThreadObject::ThreadObject()
{
	// not already in a separated thread
	playThread=0;
}
//////////////////////////////////////////////////////////////////////
ThreadObject::~ThreadObject()
{
	if (playThread!=0)
		pthread_cancel(playThread);
}
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
void ThreadObject::StartRunThreaded()
{
	// launch the thread function (class method only)
	if (playThread==0)
		pthread_create( &playThread, NULL, &ThreadObject::PlayThread, this);
	sleep(0);	// provide a chance to start the thread
}
//////////////////////////////////////////////////////////////////////
void ThreadObject::CancelThreadRun()
{

	if (playThread!=0)
		pthread_cancel(playThread);
	playThread=0;

}
//////////////////////////////////////////////////////////////////////
// static method here, no way to act with pthread as on MsWindows
//////////////////////////////////////////////////////////////////////
void *ThreadObject::PlayThread( void *ptrObject )
{
	// Start the Run method inside the object	

	pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
	pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);

	// start the code inside the objet method, not class method
	ThreadObject* play = (ThreadObject*)ptrObject ;
	play->Run();

	pthread_exit(NULL);
	play->playThread=0;
	return NULL;
}
